package com.gs.SynPatrolRep.util;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;

public class PermissionUtil {
    /**
     * 动态申请权限
     *
     * @param activity
     * @param permissions
     * @param requestCode
     * @return
     */
    public static boolean addPermission(Activity activity, String[] permissions, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissionList = new ArrayList<>();
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                    permissionList.add(permission);
                }
            }
            if (permissionList.isEmpty()) {
                return true;
            } else {
                String[] permissionNew = permissionList.toArray(new String[permissionList.size()]);
                ActivityCompat.requestPermissions(activity, permissionNew, requestCode);
                return false;
            }
        }
        return true;
    }

    /**
     * 申请权限是返回判断用户是否同意了权限
     *
     * @param grantResults
     * @return
     */
    public static boolean requestPermission(int[] grantResults) {
        return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
    }
}
